#!/usr/bin/env python
'''Find regular expression in source files'''

__author__ = "Miki Tebeka <miki.tebeka@gmail.com>"
__license__ = "BSD" # see LICENSE

from os.path import isdir
from optparse import OptionParser
from os import system

def main(argv=None):
    if argv is None:
        import sys
        argv = sys.argv

    from optparse import OptionParser

    p = OptionParser("usage: %prog [options] [DIRECTORY] REGEXP")
    p.add_option("-i", help="case insensitive search", dest="ic",
        default=0, action="store_true")
    p.add_option("-s", help="treat as source", dest="exts", action="append")

    opts, args = p.parse_args()

    if len(args) not in (1, 2):
        p.error("wrong number of arguments") # Will exit

    if len(args) == 2:
        path = args[0]
        regexp = args[1]
    else:
        path = "."
        regexp = args[0]

    if not isdir(path):
        raise SystemExit("%s: no such directory" % path)

    exts = ["*.py", "*.cgi", "*.c", "*.h", "*.js", "*.l", "*.tmpl"]
    if opts.exts:
        exts += opts.exts
    expr = " -or ".join(["-iname '%s'" % ext for ext in exts])

    ic = "i" if opts.ic else ""

    command = "find %s '(' %s ')' -exec egrep --color -%snH '%s' {} ';'" % \
            (path, expr, ic, regexp)

    raise SystemExit(system(command))

if __name__ == "__main__":
    main()
